package com.haixiaoke.saas.common.tenant;

import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.annotation.TenantScope;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租户请求拦截器
 */
@Component
public class TenantInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 判断该请求是否需要拦截(有 @ 注解才拦截)
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method != null) {
                // 获取方法上的注解
                TenantScope tenantScope = method.getMethodAnnotation(TenantScope.class);
                if (tenantScope != null) {
                    // 判断是否能从header 中获取到 TenantId
                    String tenantId = request.getHeader("X-TenantId");
                    if (StrUtil.isBlank(tenantId)) {
                        return false;
                    }
                    TenantContext.setTenantId(tenantId);

                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantContext.clearTenantId();
    }

}
